<template>
  <basic-layout>
    <custom-navbar title="图像生成" left-show />
    <div class="m-[10px]"></div>
    <div class="flex justify-center">
      <img :src="styleModel.cover" mode="widthFix" class="border-rd-[10px]" />
    </div>
    <div class="m-[20px]"></div>
    <nut-uploader
      class="justify-center"
      url="http://localhost:1002/face/upload"
      :headers="header"
      @success="uploadSuccess"
      @failure="uploadFailure"
      @delete="deleteImg"
    ></nut-uploader>

    <div class="m-[10px]"></div>
    <nut-row v-if="faceGenImgInfo && faceGenImgInfo.genStatus == 1" :span="12" :gutter="10">
      <nut-col v-for="(item, index) in faceGenImgInfo.genImgsUrl" :key="index">
        <div class="flex-content"><img :src="item" mode="widthFix" /></div>
      </nut-col>
    </nut-row>
    <div class="absolute bottom-40 left-[50%]" style="transform: translateX(-50%)">
      <nut-button type="primary" @click="startGen">开始制作</nut-button>
    </div>
  </basic-layout>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import Taro from '@tarojs/taro';
import { getFaceGenInfo } from '@/api/facegen';
import { faceGen } from '@/service/api/genImg';
import { styleInfo } from '@/api/styles';
import type { StyleModelVO } from '@/api/styles/type';
const styleModel = ref<StyleModelVO>({});
const getStyleInfo = async (id: any) => {
  const res = await styleInfo(id);
  styleModel.value = res.success;
};

const instance = Taro.getCurrentInstance();
getStyleInfo(instance.router?.params.id);

const header = ref({
  clientid: 'e5cd7e4891bf95d1d19206ce24a7b32e',
  Authorization: ``
});
const faceGenImgInfo = ref({});
const ossIds = new Array<string>();
const uploadSuccess = (res: any) => {
  // todo h5 和 小程序返回结果不一样
  const data = JSON.parse(res.data.data);
  ossIds.push(data.data.ossId);
  console.log(ossIds);
};
const uploadFailure = (res: any) => {
  console.log(res);
};
const deleteImg = (res: any) => {
  ossIds.splice(res.index, 1);
};

const queryGenInfo = async (id: any) => {
  const res = await getFaceGenInfo(id);
  faceGenImgInfo.value = res.success;
};

const startGen = async () => {
  const res = await faceGen({ ossIds, num: 5, styleId: styleModel.value.id });
  faceGenImgInfo.value = res.success;

  const timer = window.setInterval(() => {
    queryGenInfo(faceGenImgInfo.value.id);
    if (faceGenImgInfo.value.genStatus == 1) {
      clearInterval(timer);
    }
  }, 10000);
};

/** 设置页面属性 */
definePageConfig({
  navigationBarTitleText: '图像生成'
});
</script>

<style lang="scss">
.style-cover {
  border-radius: 10px;
  margin: 0 auto;
}
</style>
